package com.joseph.websocket.util;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.params.SetParams;

import java.util.Collections;
import java.util.UUID;

/**
 * redis分布式锁
 */
@Component
public class RedisLock {

    /**
     * 占用锁
     *
     * @param lockKey 锁key
     * @return 锁id
     */
    public String lock(String lockKey) {
        //获得jedis实例
        Jedis jedis = JedisUtil.getJedis();
        //锁id（必须拥有此id才能释放锁）
        String lockId = UUID.randomUUID().toString();
        //占用锁同时设置失效时间

        String isSuccees = jedis.set(lockKey, lockId, SetParams.setParams().nx().px(15000));
        //占用锁成功返回锁id，否则返回null
        if ("OK".equals(isSuccees)) {
            return lockId;
        } else {
            return null;
        }
    }

    /**
     * 释放锁
     *
     * @param lockKey 锁key
     * @param lockId  加锁id
     */
    public void unlock(String lockKey, String lockId) {
        if (lockId != null) {
            //获得jedis实例
            Jedis jedis = JedisUtil.getJedis();
            //执行Lua代码删除lockId匹配的锁
            String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
            jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonList(lockId));
        }
    }
}
